<?php


namespace App\Model\Casts;

use Hyperf\Contract\CastsAttributes;
use Carbon\Carbon;

class TimeCasts implements CastsAttributes
{
    /**
     * @inheritDoc
     */
    public function get($model, string $key, $value, array $attributes)
    {
        return $this->getTimeString($value);
    }

    /**
     * @inheritDoc
     */
    public function set($model, string $key, $value, array $attributes)
    {
        return $value;
    }

    public function getTimeString($unixTime, int $diffSec = 3600): string
    {
        if (0 == $unixTime || !is_numeric($unixTime)) {
            $unixTime = strtotime($unixTime);
        }

        if (abs(time() - $unixTime) < $diffSec) {
            return $this->timeToUtc($unixTime) . '(' . Carbon::createFromTimestamp($unixTime)->locale('zh_CN')->longRelativeDiffForHumans() . ')';
        }
        return $this->timeToUtc($unixTime);
    }

    /**
     * @param int $unixTime
     * @return false|string
     */
    private function timeToUtc(int $unixTime)
    {
        return date('Y-m-d H:i:s', $unixTime);
    }

}